package com.rong.mbt.personal.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.calanger.hh.entity.ResultView;
import com.calanger.hh.model.MedicalRecord;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.activity.base.PBaseActivity;
import com.rong.mbt.personal.adapter.MedicalRecordListAdapter;
import com.rong.mbt.personal.http.UrlApi;
import com.rong.mbt.personal.http.callback.JsonCallback;
import com.rong.mbt.personal.utils.SpUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 病例管理
 */
public class MedicalRecordListActivity extends PBaseActivity {

    private MedicalRecordListAdapter medicalRecordsListAdapter;
    private String TAG = "MedicalRecordListActivity";
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private Handler handler = new Handler();
    private boolean isLoadMore = false;//用来区分下拉刷新和上拉加载的数据添加
    private int page=1;//分页的值
    List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
    int TOTAL_COUNTER = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_recycle_view_medical_record;
    }

    @Override
    public void initView() {
        super.initView();

        refreshLayout=findViewById(R.id.swipe_refresh);
        recyclerView = findViewById(R.id.recycler_view_medical_record);

        TextView textTitle = findViewById(R.id.header_center_text);
        textTitle.setText("病例管理");
        LinearLayout back = findViewById(R.id.ll_back);
        back.setOnClickListener(v -> finish());
        LinearLayout right_ll = findViewById(R.id.right_ll);
        right_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MedicalRecordListActivity.this, MedicalRecordAddActivity.class));
            }
        });

        recyclerView.setLayoutManager(new GridLayoutManager(getApplication(), 1));
        medicalRecordsListAdapter = new MedicalRecordListAdapter();
        recyclerView.setAdapter(medicalRecordsListAdapter);

        View view= LayoutInflater.from(MedicalRecordListActivity.this)
                .inflate(R.layout.headview_layout,null);
//        medicalRecordsListAdapter.addHeaderView(view);//这是设置头部的方法，一个方法搞定，不需要跟以前一样去适配器里面判断一大堆，很方便
//    adapter.addFooterView();有头当然有尾也是一个方法搞定

        //开启动画（默认为渐显效果）
        medicalRecordsListAdapter.openLoadAnimation();

        //手动刷新 触发SwipeRefreshLayout的下拉刷新方法
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                page=1;
                loadDate(page);
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //模拟一下网络请求
//                        page=1;
//                        loadDate(page);
//                    }
//                }, 2000);
            }


        });
        medicalRecordsListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                //这个是适配器自带的上拉加载功能 很方便一个实现方法搞定
                isLoadMore = true;
                page++;
                loadDate(page);
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        //模拟一下网络请求
//                        page++;
//                        loadDate(page);
//                    }
//                }, 2000);
            }
        }, recyclerView);


        medicalRecordsListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String,Object> item = (Map<String,Object>) adapter.getItem(position);
                startActivity(new Intent(MedicalRecordListActivity.this,MedicalRecordDetailActivity.class).putExtra("singleBean",(Serializable)item));
            }

        });



        medicalRecordsListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                Map<String,Object> dataBean = (Map<String, Object>) adapter.getItem(position);
                JSONObject jsonMap = new JSONObject(dataBean);
                MedicalRecord medicalRecord =  jsonMap.getObject("medicalRecord",MedicalRecord.class);
                if(view.getId()==R.id.tv_remove){

                    AlertDialog dialog = new AlertDialog.Builder(MedicalRecordListActivity.this).setTitle("警告")
                            .setIcon(android.R.drawable.ic_dialog_info)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    remove(medicalRecord,position);

                                }
                            }).show();
                    Log.e(TAG, "AlertDialog");
                    dialog.setCanceledOnTouchOutside(false);
                }


            }
        });

    }


    @Override
    protected void onStart() {
        super.onStart();
        //控制进入是是否加载数据
//        initNet(page);
        //如果使用loadDate就有一个下拉的动作
        page = 1;
        loadDate(page);

        //自动触发下拉刷新
//        recyclerView.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                //这个方法是让一进入页面的时候实现网络请求，有个缓冲的效果
//                refreshLayout.setRefreshing(true);
//                //模拟一下网络请求
//                page=1;//page为页数
//                loadDate(page);
//            }
//        }, 100);
    }

    /**
     * 添加数据源数据  相当于网络请求
     */
    private void loadDate(int page) {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
        if (isLoadMore) {
            if(list.size()>= TOTAL_COUNTER){
//                数据全部加载完毕
                medicalRecordsListAdapter.loadMoreEnd();
            }else{
                initNet(page);
                medicalRecordsListAdapter.notifyDataSetChanged();
                medicalRecordsListAdapter.loadMoreComplete();
            }
            isLoadMore = false;
        }else{
            list.clear();
            initNet(page);
            medicalRecordsListAdapter.notifyDataSetChanged();
            medicalRecordsListAdapter.loadMoreComplete();
        }
    }

    private void initNet(int page) {
        OkGo.<ResultView>get(UrlApi.medicalRecordList)
                .tag(this)
                .headers("mbtToken", SpUtils.getToken(getApplication()))
                .params("pageNumber",page)
                .execute(new JsonCallback<ResultView>() {
                    @Override
                    public void onSuccess(Response<ResultView> response) {
                        if (response != null && response.body() != null) {
                            ResultView resultView = response.body();
//                            DoctorIndexBean body = response.body();
                            if (resultView.getData() != null) {
                                TOTAL_COUNTER = resultView.getCount();
                                List<Map<String,Object>> resultList = (List<Map<String, Object>>) resultView.getData();
                                list.addAll(resultList);
                                medicalRecordsListAdapter.setNewData(list);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<ResultView> response) {
                        super.onError(response);
                        Log.i("test", "onError   " + response.body());
                    }
                });
    }

    public void remove(MedicalRecord medicalRecord,int position){
        Log.d(TAG, "remove");
        OkGo.<ResultView>get(UrlApi.medicalRecordRemove)
                .tag(this)
                .headers("mbtToken", SpUtils.getToken(getApplicationContext()))
                .params("id", medicalRecord.getId())
                .execute(new JsonCallback<ResultView>() {
                    @Override
                    public void onSuccess(Response<ResultView> response) {

                        Log.i("medicalRecord", "delete   " + response.body());
                        ResultView resultView = response.body();
                        if (resultView.getResultCode() == 0) {
//                            initNet(page);
                            list.remove(position);
                            medicalRecordsListAdapter.setNewData(list);
                        } else {
                            Toast.makeText(MedicalRecordListActivity.this, resultView.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Response<ResultView> response) {
                        super.onError(response);
                        Log.i("medicalRecord", " delete onError   " + response.body());
                    }
                });
    }

}
